home *** CD-ROM | disk | FTP | other *** search
/ Java Certification Exam Guide / McGrawwHill-JavaCertificationExamGuide.iso / pc / Web Links and Code / code / chap21 / DB.java < prev    next >
Encoding:
Java Source  |  1997-04-20  |  1.4 KB  |  64 lines

  1. import java.io.*;
  2.  
  3. public class DB {
  4.    private static final String FILE_NAME = "test.db";
  5.    private RandomAccessFile file;
  6.    private File test;
  7.    private boolean open;
  8.  
  9.    public DB() throws IOException {
  10.       try {
  11.          test = new File(FILE_NAME);
  12.          file = new RandomAccessFile(FILE_NAME, "rw");
  13.          open = true;
  14.       } catch (IOException x) {
  15.          close();
  16.          throw x;
  17.       }
  18.    }
  19.  
  20.    public void close() {
  21.       if (open) {
  22.          try {
  23.             file.close();
  24.          } catch (IOException x) {
  25.             System.out.println(x.getMessage());
  26.          } finally {
  27.             open = false;
  28.          }
  29.       }
  30.    }
  31.  
  32.    public void finalize() throws Throwable {
  33.       close();
  34.       super.finalize();
  35.    }
  36.  
  37.    public void rewind() throws IOException {
  38.       file.seek(0);
  39.    }
  40.  
  41.    public boolean moreRecords() throws IOException {
  42.       return (file.getFilePointer() < file.length());
  43.    }
  44.  
  45.    public EmployeeRecord readRecord()
  46.       throws IOException, EOFException
  47.    {
  48.       String ssn = file.readUTF();
  49.       String name = file.readUTF();
  50.       EmployeeRecord record = new EmployeeRecord(ssn, name);
  51.  
  52.       return record;
  53.    }
  54.  
  55.    public void writeRecord(EmployeeRecord record)
  56.       throws IOException
  57.    {
  58.       file.seek(file.length());
  59.       file.writeUTF(record.getSsn());
  60.       file.writeUTF(record.getName());
  61.    }
  62.  
  63. }
  64.